package cn.wolfcode.web.modules.custinfo.controller;

import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.CityUtils;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;

import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 张创佳
 * @since 2023-09-14
 */
@Controller
@RequestMapping("custinfo")
public class TbCustomerController extends BaseController {

    @Autowired
    private ITbCustomerService entityService;

    private static final String LogModule = "TbCustomer";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {

        mv.addObject("citys",CityUtils.citys);
        mv.setViewName("cust/custinfo/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('cust:custinfo:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        mv.setViewName("cust/custinfo/add");

        //获取省份
        mv.addObject("citys", CityUtils.citys);
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('cust:custinfo:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        mv.addObject("citys",CityUtils.citys);//可以把它理解成 放到request域中
        mv.setViewName("cust/custinfo/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        return mv;
    }

    //@RequestMapping("list")
    //@PreAuthorize("hasAuthority('cust:custinfo:list')")
    //public ResponseEntity page(LayuiPage layuiPage,String parameterName) {
    //
    //    SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
    //
    //
    //
    //    IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());
    //
    //    //entityService.page(page);
    //    page = entityService.lambdaQuery().
    //            like(!StringUtils.isEmpty(parameterName),TbCustomer::getCustomerName, parameterName) //企业名称
    //            .or()
    //            .like(!StringUtils.isEmpty(parameterName),TbCustomer::getLegalLeader, parameterName) //法定代表人
    //            .page(page);
    //
    //
    //    //省份汉字
    //    //获取查询数据集合
    //    List<TbCustomer> records = page.getRecords();
    //    for (TbCustomer record : records) {
    //        String cityValue = CityUtils.getCityValue(record.getProvince());
    //        record.setProvinceName(cityValue);
    //    }
    //
    //
    //    return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    //}

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('cust:custinfo:list')")
    public ResponseEntity page(LayuiPage layuiPage, String parameterName, String cityId, String openStatus) {

        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage<TbCustomer> page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        LambdaQueryWrapper<TbCustomer> queryWrapper = new LambdaQueryWrapper<>();

        // 根据城市ID筛选
        if (!StringUtils.isEmpty(cityId)) {
            queryWrapper.eq(TbCustomer::getProvince, cityId);
        }

        // 根据开放状态筛选
        if (!StringUtils.isEmpty(openStatus)) {
            queryWrapper.eq(TbCustomer::getOpenStatus, openStatus);
        }

        // 根据参数名称模糊查询客户名称和法人负责人
        if (!StringUtils.isEmpty(parameterName)) {
            queryWrapper.and(wrapper -> wrapper
                    .like(TbCustomer::getCustomerName, parameterName)
                    .or()
                    .like(TbCustomer::getLegalLeader, parameterName)
            );
        }

        page = entityService.page(page, queryWrapper);

        // 列表所属省份查询
        List<TbCustomer> records = page.getRecords();
        for (TbCustomer record : records) {
            String cityValue = CityUtils.getCityValue(record.getProvince());
            record.setProvinceName(cityValue);
        }

        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }


    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('cust:custinfo:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbCustomer entity, HttpServletRequest request) {
        /**
         * 给实体类添加录入时间、录入人
         * */
        entity.setInputTime(LocalDateTime.now());
        //获取会话区间
        HttpSession session = request.getSession();
        //获取会话区间对象
        SysUser sysUser =  (SysUser) session.getAttribute(LoginForm.LOGIN_USER_KEY);

        //获取登录者id
        String userId = sysUser.getUserId();
        entity.setInputUserId(userId);

        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('cust:custinfo:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustomer entity) {
        entity.setUpdateTime(LocalDateTime.now());
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('cust:custinfo:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

}
